package jemuillot.BiohazardPanelPuzzle;

import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.text.Text;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.util.HorizontalAlign;

import android.view.KeyEvent;

public class LevelSelectScene extends BiohazardPanelPuzzleScene {

	private static final int LAYER_SELECTION = LAYER_BACKGROUND + 1;

	static final int LAYERS = LAYER_SELECTION + 1;

	private Text headText;

	public LevelSelectScene(BiohazardPanelPuzzle bpp) {
		super(bpp, LAYERS);

		scene.setBackgroundEnabled(false);

		scene.getLayer(LAYER_BACKGROUND).addEntity(
				new Sprite(0, 0, bpp.backgroundRegion));

		headText = new Text(0, 0, bpp.font, getString(R.string.pick_level),
				HorizontalAlign.CENTER);

		headText.setPosition(getCenterX(headText), LEVEL_PICKING_Y);

		scene.getLayer(LAYER_SELECTION).addEntity(headText);

		for (int i = 1; i < matrixLevels.length; i++) {

			String matrix;

			if (i > bpp.maxLevel)
				matrix = "?";
			else
				matrix = "" + matrixLevels[i];

			Text levelText = new Text(0, 0, bpp.font, matrix + " x " + matrix,
					HorizontalAlign.CENTER) {
				@Override
				public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
						final float pTouchAreaLocalX,
						final float pTouchAreaLocalY) {

					if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN)
						levelStart(this);
					return true;
				}
			};

			levelText.setPosition(getCenterX(levelText), LEVEL_SELECTION_Y + i
					* LEVEL_SELECTION_DY);

			scene.getLayer(LAYER_SELECTION).addEntity(levelText);

			scene.registerTouchArea(levelText);
		}

	}

	protected void levelStart(Text text) {

		int level = (int) ((text.getY() - LEVEL_SELECTION_Y) / LEVEL_SELECTION_DY);

		if (level > bpp.maxLevel) {
			bpp.sfxRejected.play();
		} else {
			new MainGameScene(bpp, level);
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			toOptions();
			return true;
		} else
			return super.onKeyDown(keyCode, event);
	}

	private void toOptions() {
		new OptionsScene(bpp);
	}
}
